/*
 * @Author: Haochen
 * @Date: 2021-11-22 15:41:04
 * @LastEditTime: 2021-11-27 16:24:08
 * @FilePath: \front\src\js\exam_detail.js
 */

import $ from './jquery-3.6.0.min.js';
import '../scss/common.scss';
import '../scss/exam-detail.scss';
import { backToIndex, getPromise, getPromiseAuthBy } from './common.js';

backToIndex();

const testId = window.location.search.substring(1).split('=').pop();

$(function () {
  const strDataQuery = '/testsRouter/:' + testId;
  // const errorDataQuery;

  async function getDataAndRender() {
    // * 获取当前考试所有的题目
    const { code, data, message } = await getPromise(strDataQuery, 'get', {});

    const exercises = data[0].exercisesId;
    const answers = exercises.map((exercise) => exercise.answer);

    const users = JSON.parse(localStorage.getItem('users'));
    const userId = users.find((user) => user.status === 'online')._id;

    // * 找到当前学生所有的错题
    let {
      code: code1,
      data: data1,
      message: message1,
    } = await getPromise('/testedsRouter/:' + userId, 'get', {});

    // * 筛选当前考试的错题-根据考试id
    let testeds = data1;

    let tested = testeds.filter((tested) => tested.testId._id == testId)[0];

    const studentAnswers = tested.options.map((option) => parseInt(option));

    // * 比较两方答案
    const arr = new Array(answers.length);
    for (let i = 0; i < arr.length; i++) {
      arr[i] = answers[i] === studentAnswers[i] ? 1 : -1;
    }
    console.log(answers);
    console.log(studentAnswers);
    render(data, arr, answers, studentAnswers);
  }

  getDataAndRender();

  function render(data, array, answers, stdAnswers) {
    const examType = data[0].typeId.type;
    const examTitle = data[0].title;

    const exercises = data[0].exercisesId;
    const MAX_NUM_Q = exercises.length;

    for (let i = 0; i < answers.length; i++) {
      switch (answers[i]) {
        case 0:
          answers[i] = 'A';
          break;
        case 1:
          answers[i] = 'B';
          break;
        case 2:
          answers[i] = 'C';
          break;
        case 3:
          answers[i] = 'D';
          break;
      }
    }

    for (let i = 0; i < stdAnswers.length; i++) {
      switch (stdAnswers[i]) {
        case -1:
          stdAnswers[i] = '无';
          break;
        case 0:
          stdAnswers[i] = 'A';
          break;
        case 1:
          stdAnswers[i] = 'B';
          break;
        case 2:
          stdAnswers[i] = 'C';
          break;
        case 3:
          stdAnswers[i] = 'D';
          break;
      }
    }

    $('.nav-main').append(`
      <h3>${examTitle}</h3>
    `);
    $('.exam-type').text(`${examType}`);

    $('.total').text(MAX_NUM_Q);
    $('.unanswered').text(countQuestionUnanswered(stdAnswers, MAX_NUM_Q));

    for (let i = 0; i < array.length; i++) {
      if (array[i] === 1) {
        $('.sb-box-3').append(`
          <div class="rect-box correct-box" boxnum = "${i}">${i + 1}</div>
      `);

        $('.content-question').append(`

         <div class="question-context" order="${i}">

            <h5 class="question-text">
                ${exercises[i].topics}
            </h5>
                    <ul class="answers">
                        <li answerIndex="0">
                            <div class="circle-box">A</div>
                            <span class="answer-text">${exercises[i].options[0]}</span>
                        </li>
                        <li answerIndex="1">
                            <div class="circle-box">B</div>
                            <span class="answer-text">${exercises[i].options[1]}</span>
                        </li>
                        <li answerIndex="2">
                            <div class="circle-box">C</div>
                            <span class="answer-text">${exercises[i].options[2]}</span>
                        </li>
                        <li answerIndex="3">
                            <div class="circle-box">D</div>
                            <span class="answer-text">${exercises[i].options[3]}</span>
                        </li>
                    </ul>

        </div>

         <div class="question-detail">
                        <ul id="qd-items">
                            <li>考生答案：</li>
                            <li>正确答案：</li>
                            <li>解析：</li>
                        </ul>
                        <ul>
                            <li class='user-answer correct'>${stdAnswers[i]}</li>
                            <li class="correct-answer correct">${answers[i]}</li>
                            <li>
                                ${exercises[i].analysis}
                            </li>
                        </ul>
        </div>

      `);
      } else {
        $('.sb-box-3').append(`
          <div class="rect-box wrong-box" boxnum = "${i}">${i + 1}</div>
      `);

        $('.content-question').append(`

         <div class="question-context" order="${i}">

            <h5 class="question-text">
                ${exercises[i].topics}
            </h5>
                    <ul class="answers">
                        <li answerIndex="0">
                            <div class="circle-box">A</div>
                            <span class="answer-text">${exercises[i].options[0]}</span>
                        </li>
                        <li answerIndex="1">
                            <div class="circle-box">B</div>
                            <span class="answer-text">${exercises[i].options[1]}</span>
                        </li>
                        <li answerIndex="2">
                            <div class="circle-box">C</div>
                            <span class="answer-text">${exercises[i].options[2]}</span>
                        </li>
                        <li answerIndex="3">
                            <div class="circle-box">D</div>
                            <span class="answer-text">${exercises[i].options[3]}</span>
                        </li>
                    </ul>

        </div>

         <div class="question-detail">
                        <ul id="qd-items">
                            <li>考生答案：</li>
                            <li>正确答案：</li>
                            <li>解析：</li>
                        </ul>
                        <ul>
                            <li class='user-answer wrong'>${stdAnswers[i]}</li>
                            <li class="correct-answer correct">${answers[i]}</li>
                            <li>
                                ${exercises[i].analysis}
                            </li>
                        </ul>
        </div>

      `);
      }

      if (i > 0) {
        $(`.question-context:eq(${i})`).hide();
        $(`.question-detail:eq(${i})`).hide();
      }
    }

    let cur_i = $(`.question-context:visible`).attr('order'); // * 当前所在题目的下标

    // * 跳到指定题目
    $('.sb-box-3').on('click', '.rect-box', function () {
      //   cur_i = parseInt($(`.question-context:visible`).attr('order'));

      cur_i = parseInt($(this).attr('boxnum')); // 点击右侧边栏的小盒子所对应的题目下标

      $('.order').text(`${cur_i + 1}`);
      $(`.question-context`).hide();
      $(`.question-detail`).hide();
      $(`.question-context:eq(${cur_i})`).fadeIn(1000);
      $(`.question-detail:eq(${cur_i})`).fadeIn(1000);
    });

    // * 跳到下一题
    // let clickCount = 0;
    $('#btn-next-question').click(function () {
      // console.log('click', ++clickCount, 'time(s)');
      if (cur_i < MAX_NUM_Q - 1) {
        cur_i = parseInt($(`.question-context:visible`).attr('order'));

        $(`.question-context:eq(${cur_i})`).hide();
        $(`.question-detail:eq(${cur_i})`).hide();
        $(`.question-context:eq(${cur_i + 1})`).fadeIn(1000);
        $(`.question-detail:eq(${cur_i + 1})`).fadeIn(1000);

        cur_i = parseInt($(`.question-context:visible`).attr('order'));

        $('.order').text(cur_i + 1);

        return true;
      } else {
        alert('已经是最后一题');

        return false;
      }
    });
  }
});

function countQuestionUnanswered(answers, initialCount) {
  let answered = 0;
  for (const answer of answers) {
    if (answer !== -1) answered++;
  }
  return '' + (initialCount - answered);
}

$('#btn-add-collection').click(async function () {
  const exerciseId = $(
    '.content .content-question .question-context:visible'
  ).attr('exercise-id');
  const testId = $('.content .content-question .question-context:visible').attr(
    'test-id'
  );
  const errorId = $(
    '.content .content-question .question-context:visible'
  ).attr('error-id');

  console.log(exerciseId, testId, errorId);
  //   const studentId = userId;
  //   let { code, data, message } = await getPromise('/collectionsRouter', 'post', {
  //     studentId,
  //     exerciseId,
  //     testId,
  //     errorId,
  //   });

  //   alert(message);
});
